import { Pagination } from "ant-design-vue";
import { nextTick, ref, type FunctionalComponent } from "vue";

export function usePagination (fn: (page: number, size: number) => Promise<any>) {
  const pageState = ref({ pageNumber: 1, pageSize: 10, total: 0, totalPages: 0 });
  const loading = ref(false);
  async function getList (page?: number, size?: number) {
    loading.value = true;
    if (!page) {
      page = pageState.value.pageNumber;
    }
    if (!size) {
      size = pageState.value.pageSize;
    }
    const { total, totalPages } = await fn(page, size).finally(() => {
      loading.value = false;
    });
    pageState.value.total = total || 0;
    pageState.value.totalPages = totalPages || 0;
    nextTick(() => {
      pageState.value.pageNumber = page || 1;
      pageState.value.pageSize = size || 10;
    });
  }
  const MyPagination:FunctionalComponent = (props, ctx) =>
    <div class="flex justify-between items-center">
      <div>
        {ctx.slots.default?.()}
      </div>
      <Pagination showQuickJumper total={pageState.value.total} onChange={getList} current={pageState.value.pageNumber} pageSize={pageState.value.pageSize}>
      </Pagination>
    </div>;
  return { pageState, getList, MyPagination, loading };
}
